# -*- coding: UTF-8 -*-
import pymssql
import _mssql
import json
import requests
import sys
from datetime import date, datetime
from uuid import UUID
import decimal

def __default(obj):
    if isinstance(obj, datetime):
        return obj.strftime('%Y-%m-%d %H:%M:%S')
    elif isinstance(obj, date):
        return obj.strftime('%Y-%m-%d')
    elif isinstance(obj, UUID):
        return str(obj)
    elif isinstance(obj, decimal.Decimal):
        return float(obj)
    else:
        raise TypeError('%r is not JSON serializable' % obj)

reload(sys)   
sys.setdefaultencoding('utf8')


connlock=pymssql.connect(host='.',database='scm_main')
curlock=connlock.cursor()

curlock.execute('update ty_lock set id=1 where id=1')

conn=pymssql.connect(host='.',database='scm_main')
#conn=pymssql.connect(host='127.0.0.1',user='sa',password='Sa@1',database='scm_main')
cur=conn.cursor(as_dict=True)

dwID=''
with open(sys.path[0]+'/dwid', 'r') as f:
        dwID=f.read()



while True:
    cur.execute(u'select top 100 ' + dwID + ' dw,jl_sj sj,ISNULL(user_serial,0) user_serial,mc dev_name,xh from view_nt_mj where not exists ( select 1 from ty_mj where id = xh)')

    
    d=cur.fetchall()
   
    if len(d)>0:
        jsonData = []
        for i, val in enumerate(d):
            jsonData.append(val['xh'])

        payload = {'cards':json.dumps(d,default=__default,ensure_ascii=False)}
        #print payload

        r = requests.post("http://wx.nttengyuan.com:81/ty/sync/saveKQ.do", data=payload)

        rs=json.loads(r.text)


        if r.status_code==200 and rs['success'] :
            cur.executemany("INSERT INTO ty_mj VALUES (%d)",jsonData)
            # you must call commit() to persist your data if you don't set autocommit to True
            conn.commit()
        print u'同步门禁记录',len(d),u'条'
    else:
        print u'没有需要同步数据'
        break

cur.close()
conn.close()

connlock.commit()
curlock.close()
connlock.close()



